<template>
  <div class="search-bar">
    <a-space>
      <a-input-search v-model:value.trim="query.keywords" placeholder="输入租户名称搜索" style="width: 300px"
        @search="handleSearch" />
      <a-button type="primary" @click="handleCreate">新增租户</a-button>
    </a-space>
  </div>

  <a-table :columns="columns" :data-source="dataSource" :pagination="pagination" @change="pagination.handleChange"
    row-key="id" bordered class="data-content">
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.key === 'index'">
        {{ index + 1 }}
      </template>
      <template v-if="column.key === 'enabled'">
        <a-tag :color="record.enabled ? 'green' : 'red'">
          {{ record.enabled ? '启用' : '禁用' }}
        </a-tag>
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space :size="8">
          <a-button type="link" size="small" @click="handleEditTenant(record)">编辑</a-button>
          <a-popconfirm title="确定要删除这个租户吗？" ok-text="确定" cancel-text="取消" @confirm="handleDeleteTenant(record)">
            <a-button type="link" size="small" danger>删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </a-table>

  <a-modal destroyOnClose :keyboard="false" :okButtonProps="{loading:dialogEditor.loading}" v-model:open="dialogEditor.open" :title="dialogEditor.title" @ok="handleOk" @cancel="handleCancel"
    width="800px">
    <tenant-editor ref="editorRef" :id="dialogEditor.id" />
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import TenantEditor from './components/editor.vue';
import { TenantApi } from '@/api/services/index';
import { GetTenantInput, TenantDto } from '@/api/services/types';
import { ClientPagination, createPagedQuery, IDialogProps } from '@/api/abp';




const pagination = ref<ClientPagination>(new ClientPagination(() => {
  loadData();
}))
const dataSource = ref<Array<TenantDto>>([])
const query = reactive<GetTenantInput>({
  keywords: '',
  readOnly: true,
  sorting: 'creationTime desc,lastModificationTime desc',
  skipCount: 0,
  maxResultCount: 20
})
const dialogEditor = reactive<IDialogProps>({
  id: '',
  open: false,
  data: undefined,
  title: '',
  loading: false
})
const editorRef = ref<InstanceType<typeof TenantEditor>>();

const loadData = function () {
  const input = createPagedQuery(pagination.value, query);
  TenantApi.getList(input).then(res => {
    const { code, data, msg } = res;
    if (code === 0) {
      dataSource.value = data.items || [];
      pagination.value.total = data.totalCount;
      pagination.value.readOnly = true;
    } else {
      message.error(msg || '加载数据失败');
    }
  })
}

import { debounce } from 'lodash-es'

const handleSearch = debounce(() => {
  pagination.value.current = 1
  loadData();
}, 300)

const handleCreate = function () {
  dialogEditor.id = '';
  dialogEditor.title = '新增租户';
  dialogEditor.open = true;
}

const handleEditTenant = function (record: TenantDto) {
  dialogEditor.id = record.id;
  dialogEditor.title = '修改租户';
  dialogEditor.open = true;
}

const handleDeleteTenant = function (record: TenantDto) {
  TenantApi.delete(record.id).then(res => {
    const { code, msg } = res;
    if (code === 0) {
      message.success('删除成功');
      pagination.value.readOnly = false;
      loadData();
    } else {
      message.error(msg || '删除失败');
    }
  }).catch(() => {
    message.error('网络错误，请稍后重试');
  })
}


const handleOk = async () => {
  dialogEditor.loading = true;
  editorRef.value?.submit().then(res => {
    const { code, msg } = res;
    if (code === 0) {
      dialogEditor.open = false;
      dialogEditor.id = '';
      message.success('保存成功')
      pagination.value.readOnly = false;
      loadData();
    } else {
      message.error(msg || '保存失败');
    }
  }).finally(() => {
    dialogEditor.loading = false;
  })

};

const handleCancel = () => {
  dialogEditor.loading = false;
  dialogEditor.id = '';
  dialogEditor.open = false;

};




onMounted(() => {
  loadData();
})

import type { TableColumnsType } from 'ant-design-vue'

const columns: TableColumnsType<TenantDto> = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    width: 70
  },
  {
    title: '租户名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '显示名称',
    dataIndex: 'displayName',
    key: 'displayName'
  },
  {
    title: '联系人',
    dataIndex: 'contractName',
    key: 'contractName'
  },
  {
    title: '联系电话',
    dataIndex: 'contractPhone',
    key: 'contractPhone'
  },
  {
    title: '状态',
    dataIndex: 'enabled',
    key: 'enabled'
  },
  {
    title: '操作',
    key: 'action',
    width: 150
  }
];

</script>

<style lang="scss" scoped>
.tenant-container {
  padding: 20px;
  background: #fff;
}

.search-bar {
  margin-bottom: 20px;
}

.data-content {
  flex: 1;

  .ant-table {
    flex: 1;
  }
}
</style>
